import {useEffect, useState} from 'react';
import {Button, Upload, Image} from "antd";
import {UploadOutlined} from '@ant-design/icons';
import {uploadPublic} from "@/axios/apis.ts";
import type {GetProp, UploadFile, UploadProps} from 'antd';

const CustomUpload = (props) => {
    const {listType = 'text', getFiles, maxCount = 1, initData, moduleName = 'webusersys', showUploadList = true } = props
    const [fileList, setFileList] = useState<UploadFile[]>([])
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const handleChange: UploadProps['onChange'] = ({file, fileList}) => {
        setFileList(fileList); // 受控模式更新
    };

    const customRequest = async (event) => {
        const {file, onProgress, onSuccess, onError} = event;
        const formData = new FormData();
        formData.append("file", file);
        formData.append("module", moduleName);
        uploadPublic(formData).then(res => {
            if (+res.code === 200) {
                onSuccess(res.data, event.file); //上传成功监听事件
            }
        })
    };
    const handlePreview = async (file: UploadFile) => {
        if (!file.response) return
        if (['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'].includes(file.type)) {
            setPreviewImage(import.meta.env.VITE_BASE_IMG + file.response)
            setPreviewOpen(true);
        }
    };
    useEffect(() => {
        getFiles(fileList.reduce((res, ite) => {
            if (ite.response) {
                res.push({url: ite.response, name: ite.name, type: ite.type})
            }
            return res
        }, []))
    }, [fileList]);
    useEffect(() => {
        if (typeof initData === 'string') {
            setFileList([{url: initData, name: '图片', type: 'image/png', uid: Date.now() + ''}])
        }
    }, [initData]);
    return (
        <Upload
            customRequest={customRequest}
            fileList={fileList}
            listType={listType}
            onPreview={handlePreview}
            disabled={previewOpen}
            onChange={handleChange}
            maxCount={maxCount}
            showUploadList={showUploadList}
        >
            {props.children ? props.children : <Button type="primary" icon={<UploadOutlined />}>点击上传</Button>}
            {previewImage && (
                <Image
                    wrapperStyle={{display: 'none'}}
                    preview={{
                        visible: previewOpen,
                        onVisibleChange: (visible) => setPreviewOpen(visible),
                        afterOpenChange: (visible) => !visible && setPreviewImage(''),
                    }}
                    src={previewImage}
                />
            )}
        </Upload>
    );
};

export default CustomUpload;